package com.cc.flyingfish.filter;

import com.cc.flyingfish.util.TokenParseUtil;
import org.apache.http.HttpStatus;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author CHENCHEN
 * @company 北京学佳澳教育科技
 * @create 2023-03-01 13:49
 */
public class HeaderTokenGatewayFilter implements GatewayFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求中
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if(!token.isEmpty()){
            try {
                //解析Token获取用户信息
                TokenParseUtil.parseUserInfoFromToken(token);
                return chain.filter(exchange);
            }catch (Exception e){
                throw new RuntimeException("token异常");
            }
        }
        //标记没有权限，并结束这次请求
        exchange.getResponse().setRawStatusCode(HttpStatus.SC_UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return HIGHEST_PRECEDENCE + 2;
    }
}
